package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import service.VisitorRegisterService;
import util.ServiceException;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;

@Controller
@RequestMapping("visitor")
public class register {

    @Autowired
    private VisitorRegisterService visitorRegisterService;

    @RequestMapping("register")
    public ModelAndView register(HttpServletRequest request) throws ParseException {
        String action = request.getParameter("action");

        System.out.println("-----r----"+action);
        ModelAndView mav=new ModelAndView();

        if("active".equals(action)) {
            //激活
            String email = request.getParameter("email");//获取email
            String code = request.getParameter("code");//激活码
            try {
                visitorRegisterService.processActivate(email , code);//调用激活方法
                mav.setViewName("/jsp/active_success.jsp");
            } catch (ServiceException e) {
                request.setAttribute("message" , e.getMessage());
                mav.setViewName("/jsp/active_failed.jsp");
            } catch (javax.mail.internet.ParseException e) {
                e.printStackTrace();
            }
        } else if("register".equals(action)) {
            //注册
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            try {
                visitorRegisterService.processregister(email,password,request);//发邮箱激活
                mav.addObject("text","注册成功");
                mav.setViewName("/jsp/register_success.jsp");
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }

        return mav;
    }


}
